#include "svmClassifyData.h"
#include <cctype>

void svmClassifyData::readSvm(char * testingFilename) {
	FILE* inputFilePointer = fopen(testingFilename, "r");
	if (inputFilePointer == NULL) {
		printf("!!!!!SVM file not found:%s\n",testingFilename);
		exit(1);
	}

	line = (char*)malloc(max_line_len);
	
	//Scan the input data to get the dimension and # of training points.
	while(readline(inputFilePointer)!=NULL)
	{
		char *p = strtok(line," \t");
		while(1)
		{
			p = strtok(NULL," \t");
			if(p == NULL || *p == '\n')
				break;
			int tempDim = atoi(p); //addition char':' will be ignored
			if(tempDim > nDimension) {
				nDimension = tempDim;
			}
		}
		nPoints++;
	}

	// Rewind and prepare for next scan.
	rewind(inputFilePointer); 

	printf("> Input data found: %d points, %d dimension\n", nPoints, nDimension);

	//According to the information of dimension and # of training points, allocate host memory to store the data.
	data = (float*)malloc(sizeof(float)*nPoints*nDimension);
	memset(data,0,nPoints*nDimension*sizeof(float));
	labels = (int*)malloc(sizeof(int)*nPoints);

	//transposeData = (float*)malloc(sizeof(float)*nPoints*nDimension);
	//memset(transposeData,0,sizeof(float)*nPoints*nDimension);
	
	char * endPtr;
	for(int i=0;i<nPoints;i++) {
		int instMaxIndex = -1;
		readline(inputFilePointer);
		char * cLabel = strtok(line," \t");
		labels[i] = (int)strtol(cLabel,&endPtr,10);
		if(endPtr == cLabel)
			exitInputError(i+1);
		while(1) {
			char * cIdx = strtok(NULL,":");
			char * cVal = strtok(NULL," \t");

			if(cVal == NULL) break;

			errno = 0;
			int idx = (int)strtol(cIdx,&endPtr,10);
			if(endPtr == cIdx || errno !=0 || *endPtr != '\0' || idx <= instMaxIndex)
				exitInputError(i+1);
			else
				instMaxIndex = idx;

			errno = 0;
			float val = (float)strtod(cVal,&endPtr);
			if(endPtr == cVal || errno !=0 || (*endPtr != '\0' && !isspace(*endPtr)))
				exitInputError(i+1);
			data[(idx-1)*nPoints+i] = val;
			//transposeData[i*nDimension+idx-1] = val;
		}
	}
	free(line);
	fclose(inputFilePointer);
	return;
}

void svmClassifyData::cleanData() {
	free(labels);
	free(data);
}

//void svmClassifyData::printClassification(const char* outputFile, float* result, int nPoints) {
//	FILE* outputFilePointer = fopen(outputFile, "w");
//	if (outputFilePointer == NULL) {
//		printf("Can't write %s\n", outputFile);
//		exit(1);
//	}
//	for (int i = 0; i < nPoints; i++) {
//		fprintf(outputFilePointer, "%f\n", result[i]);
//	}
//	fclose(outputFilePointer);
//}
